package com.shop.servlet.book;

import com.mysql.jdbc.StringUtils;
import com.shop.pajo.Book;
import com.shop.service.book.BookServiceImpl;
import com.shop.service.book.IBookService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class BookServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if(method != null && method.equals("query")){
            this.query(req,resp);
        }else if (method != null && method.equals("add")){
            this.add(req,resp);
        }else if (method != null && method.equals("toUpdate")){
            this.toUpdate(req,resp);
        }else if (method != null && method.equals("update")){
            this.update(req,resp);
        }else if (method != null && method.equals("delete")){
            this.delete(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }

    public void query(HttpServletRequest req, HttpServletResponse resp) {
        IBookService bookService = new BookServiceImpl();
        String selectChoice = req.getParameter("selectChoice");
        String queryData = req.getParameter("queryData");
        List<Book> bookList = null;
        if(selectChoice != null && selectChoice.equals("bName")){
            bookList = bookService.query(queryData,null);
        }else if(selectChoice != null && selectChoice.equals("bCode")){
            bookList = bookService.query(null,queryData);
        }else {
            bookList = bookService.query(null,null);
        }
        req.setAttribute("bookList",bookList);
        try {
            req.getRequestDispatcher("/jsp/admin/bookAdmin.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void add(HttpServletRequest req, HttpServletResponse resp){
        //判断上传的文件是普通表单还是文件表单
        if(!ServletFileUpload.isMultipartContent(req)){
            return; //终止方法运行，说明这是一个普通表单
        }
        String uploadPath = this.getServletContext().getRealPath("/image/bookImage");
        File uploadFile = new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();
        }

        //缓存，临时文件
        String tmpPath = this.getServletContext().getRealPath("/image/bookTemp");
        File file = new File(tmpPath);
        if(!file.exists()){
            file.mkdir();
        }

        //1.获取工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        factory.setRepository(file);
        //2.获取servletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int PItems) {
                System.out.println("总大小：" + pContentLength + "已上传：" + pBytesRead);
            }
        });
        upload.setHeaderEncoding("UTF-8");  //处理乱码
        upload.setFileSizeMax(1024 * 1024 * 10);//单个文件最大值
        upload.setSizeMax(1024 * 1024 * 10);

        //3.处理文件
        List<String> list = null;
        String uuidPath = null;
        try {
            //解析前端请求，封装成一个FileItem对象，需要从ServletFileUpload对象获取
            //ServletFileUpload负责将每一个输入对象封装成fileItems对象
            List<FileItem> fileItems = upload.parseRequest(req);
            list = new ArrayList<>();
            for (FileItem fileItem : fileItems) {
                //判断是不是文件表单
                if(fileItem.isFormField()){
                    String temp = fileItem.getString("UTF-8");
                    list.add(temp);
                }else {
                    //是文件
                    String uploadName = fileItem.getName();
                    //可能存在文件名不合法清空
                    if(uploadName.trim().equals("") || uploadName == null){
                        continue;
                    }

                    //使用UUID产生一个唯一名称
                    uuidPath = UUID.randomUUID().toString() + ".jpg";
                    String realPath = uploadPath + "/" + uuidPath;

                    InputStream inputStream = fileItem.getInputStream();
                    //创建输出流
                    FileOutputStream fos = new  FileOutputStream(realPath);
                    byte[] buffer = new byte[1024*1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) > 0){
                        fos.write(buffer,0,len);
                    }
                    fos.close();
                    inputStream.close();

                    fileItem.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        IBookService bookService = new BookServiceImpl();
        Book book = new Book();
        String bid =  list.get(0);
        String bName = list.get(1);
        String bAuthor = list.get(2);
        String bPress = list.get(3);
        String bPrice = list.get(4);
        String bQuantity = list.get(5);
        book.setId(bid);
        book.setName(bName);
        book.setAuthor(bAuthor);
        book.setPress(bPress);
        book.setPicture(uuidPath);
        book.setPrice(new BigDecimal(bPrice).setScale(2,BigDecimal.ROUND_DOWN));
        book.setQuantity(new BigDecimal(bQuantity).setScale(2,BigDecimal.ROUND_DOWN));
        int addNum = bookService.add(book);
        if(addNum > 0){
            req.setAttribute("tips","添加成功");
        }else {
            req.setAttribute("error","添加失败");
        }
        try {
            req.getRequestDispatcher("/jsp/admin/bookAdminAdd.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void toUpdate(HttpServletRequest req, HttpServletResponse resp){
        String bid = req.getParameter("bid");
        if (!StringUtils.isNullOrEmpty(bid)) {
            IBookService bookService = new BookServiceImpl();
            Book book = bookService.getBookById(bid);
            req.setAttribute("book",book);
            try {
                req.getRequestDispatcher("/jsp/admin/bookAdminUpdate.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void update(HttpServletRequest req, HttpServletResponse resp){
        //判断上传的文件是普通表单还是文件表单
        if(!ServletFileUpload.isMultipartContent(req)){
            return; //终止方法运行，说明这是一个普通表单
        }
        String uploadPath = this.getServletContext().getRealPath("/image/bookImage");
        File uploadFile = new File(uploadPath);
        if(!uploadFile.exists()){
            uploadFile.mkdir();
        }

        //缓存，临时文件
        String tmpPath = this.getServletContext().getRealPath("/image/bookTemp");
        File file = new File(tmpPath);
        if(!file.exists()){
            file.mkdir();
        }

        //1.获取工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(1024 * 1024);
        factory.setRepository(file);
        //2.获取servletFileUpload
        ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setProgressListener(new ProgressListener() {
            @Override
            public void update(long pBytesRead, long pContentLength, int PItems) {
                System.out.println("总大小：" + pContentLength + "已上传：" + pBytesRead);
            }
        });
        upload.setHeaderEncoding("UTF-8");  //处理乱码
        upload.setFileSizeMax(1024 * 1024 * 10);//单个文件最大值
        upload.setSizeMax(1024 * 1024 * 10);

        //3.处理文件
        List<String> list = null;
        String uuidPath = null;
        try {
            //解析前端请求，封装成一个FileItem对象，需要从ServletFileUpload对象获取
            //ServletFileUpload负责将每一个输入对象封装成fileItems对象
            List<FileItem> fileItems = upload.parseRequest(req);
            list = new ArrayList<>();
            for (FileItem fileItem : fileItems) {
                //判断是不是文件表单
                if(fileItem.isFormField()){
                    String temp = fileItem.getString("UTF-8");
                    list.add(temp);
                }else {
                    //是文件
                    String uploadName = fileItem.getName();
                    //可能存在文件名不合法清空
                    if(uploadName.trim().equals("") || uploadName == null){
                        continue;
                    }

                    //使用UUID产生一个唯一名称
                    uuidPath = UUID.randomUUID().toString() + ".jpg";
                    String realPath = uploadPath + "/" + uuidPath;

                    InputStream inputStream = fileItem.getInputStream();
                    //创建输出流
                    FileOutputStream fos = new  FileOutputStream(realPath);
                    byte[] buffer = new byte[1024*1024];
                    int len = 0;
                    while ((len = inputStream.read(buffer)) > 0){
                        fos.write(buffer,0,len);
                    }
                    fos.close();
                    inputStream.close();

                    fileItem.delete();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        IBookService bookService = new BookServiceImpl();
        Book book = new Book();
        String bid =  list.get(0);
        String bName = list.get(1);
        String bAuthor = list.get(2);
        String bPress = list.get(3);
        String bPrice = list.get(4);
        String bQuantity = list.get(5);
        book.setId(bid);
        book.setName(bName);
        book.setAuthor(bAuthor);
        book.setPress(bPress);
        book.setPicture(uuidPath);
        book.setPrice(new BigDecimal(bPrice).setScale(2,BigDecimal.ROUND_DOWN));
        book.setQuantity(new BigDecimal(bQuantity).setScale(2,BigDecimal.ROUND_DOWN));

        int updateNum = bookService.update(book,this.getServletContext().getRealPath("/image/bookImage"));

        if(updateNum > 0){
            req.setAttribute("tips","修改成功");
        }else {
            req.setAttribute("error","修改失败");
        }

        try {
            req.getRequestDispatcher("/jsp/admin/book.do?method=toUpdate&bid="+book.getId()).forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    public void delete(HttpServletRequest req, HttpServletResponse resp) {
        IBookService bookService = new BookServiceImpl();
        String bid = req.getParameter("bid");
        int deleteNum = bookService.delete(bid, this.getServletContext().getRealPath("/image/bookImage"));
        if(deleteNum > 0){
            req.setAttribute("tips","删除成功");
        }else {
            req.setAttribute("error","删除失败");
        }
        try {
            req.getRequestDispatcher("/jsp/admin/book.do?method=query").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
